/*
* 业务模块
* */
const mysql = require("mysql")
const path = require("path")
const fs = require("fs")
const db = require("./db")

//自动生成图书编号(自增)
let maxBookCode = () => {
    let arr = []
    data.forEach((item)=>{
        arr.push(item.id)
    })
    return Math.max.apply(null, arr)
}

//渲染主页
exports.showIndex = (req, res) => {
    let sql = "select * from book"
    db.base(sql, null, (result) =>{
        res.render('index', {list : result})
    })
}

exports.toAddBook = (req, res) => {
    res.render('addBook', {})
}

exports.addBook = (req, res) => {

    let info = req.body  //获取表单数据
    let book = {}
    for(let key in info){
        book[key] = info[key]
    }

    let sql = "insert into book set ?"
    db.base(sql, book, (result)=>{
        if(result.affectedRows === 1){
            res.redirect("/")  //文件写入成功 成功跳转到主页面
        }
    })
}

//跳转修改图书的页面
exports.toEditBook = (req, res) => {
    let id = req.query.id   // 获取传递过来的id
    let sql = "select * from book where id=?"
    let data = [id]
    db.base(sql ,data, (result)=>{
        res.render('editBook', result[0])
    })
}

//修改图书数据
exports.editBook = (req, res) => {
    let info = req.body
    let sql = "update book set name=?, author=?, category=?, description=? where id=?"
    let data = [info.name, info.author, info.category, info.description, info.id]
    db.base(sql, data, (result)=>{
        if(result.affectedRows === 1){
            res.redirect("/")  //文件写入成功 成功跳转到主页面
        }
    })
}

//

exports.deleteBook = (req, res) => {
    let id = req.query.id   // 获取传递过来的id
    let sql = "delete from book where id=?"
    let data = [id]
    db.base(sql, data, (result)=>{
        if(result.affectedRows === 1){
            res.redirect("/")  //文件写入成功 成功跳转到主页面
        }
    })
}